<?php
namespace app\index\controller;

use app\common\controller\IndexBase;
use think\Controller;
use think\Db;
use app\common\model\Order;
use app\common\controller\Alipay;
use app\common\controller\WeiXinpay;
use app\common\model\OrderLog;
use think\facade\Session;
use think\cache\driver\Redis;

/**
 * 后台首页
 * Class Index
 * @package app\admin\controller
 */
class Pay extends IndexBase
{
    protected function initialize()
    {
        parent::initialize();
    }

    public function pay(){
        if($this->request->isPost()){
            $data = $this->request->post();
            if(empty($data['sign'])){
                $this->error('sign不能为空');
            }
            if(empty($data['type'])){
                $this->error('请选择支付方式');
            }
            if(empty($data['amount']) || $data['amount'] <= 0){
                $this->error('支付金额错误');
            }
            if(empty($data['goods_name'])){
                $this->error('商品名称不能为空');
            }
            //校验提交的游戏id、uid、cid
            if(empty($data['gid']) || $data['gid'] != $this->gid){
                $this->error('游戏id错误');
            }
            $grr = [30];
            $uid = $this->uid;
            if(in_array($data['gid'], $grr)){
                $player_old = DB::connect('db_config_aiqi')->name('player_old')->where(['banma_id'=>$data['uid']])->find();
//                $player_old = get_player_by_account($data['uid']);
                if($player_old){
                    $this->uid = $player_old['banma_id'];
                }
            }

            $old_grr = [81,82,83,84,85,86,87,88,86,91,
                92,93,94,95,96,97,98,99,100,101,102];

            if(in_array($data['gid'], $old_grr)){
                $player_old = DB::connect('db_config_aiqi')->name('jinling_palyer')->where(['old_id'=>$data['uid']])->find();
                if($player_old){
                    $this->uid = $player_old['old_id'];
                }
            }

            if(empty($data['uid']) || $data['uid'] != $this->uid){
                $this->error('用户id错误');
            }
            if(!empty($data['cid']) && $data['cid'] != $this->cid){
                $this->error('游戏渠道id错误');
            }
            $type = $data['type'];
            $is_aiqi_cid = $data['is_aiqi_cid'];
            unset($data['type']);
            unset($data['cid']);
            unset($data['is_aiqi_cid']);
            unset($data['token']);

            if(!$this->checkSign($data,2)){
                $this->error('签名错误');
            }
            $data['type'] = $type;
            $data['num'] = $data['num'] ?? 1;
            $data['sid'] = $data['sid'] ?? 0;
            $data['uid'] = $uid;
            $data['gid'] = $this->gid;
            $data['cid'] = $this->cid;
            $device = detectDevice();
            try {
                //创建订单
                $order = $this->create_order($data);
                $order['user_id'] = $uid;
                if($data['type'] == 1){
                    //支付宝支付
                    $result = $this->alipay($order, $is_aiqi_cid);
                    return $result;
                }else if($data['type'] == 2){
                    //微信支付
                    if(is_weixin()){
                        $result = $this->wx_pay_jsapi($order);
                    }else{
                        $result = $this->wechat($order,$device);
                    }

                    return $result;
                }
            }catch (\Exception $e){
                $this->error($e->getMessage());
            }

        }
    }

    public function pay_query()
    {
        return $this->fetch('game/pay_query', ['order_no' => $this->request->route('order_no'), 'gid' => $this->request->route('gid')]);
    }

    public function order_query()
    {
        $orderNo = $this->request->post('order_no');
        $order = Order::where('order_no', $orderNo)->find();
        if(empty($order)){
            return [
                'code' => 0,
                'msg' => '订单不存在',
                'data' => [],
            ];
        }

        if($order['type'] == 1){// 支付宝
            $result = $this->alipay_query($orderNo);
        }elseif ($order['type'] == 2){// 微信
            $result = $this->wechat_query($orderNo);
        }
        return $result;

    }

    protected function create_order($data)
    {
        $data['order_no'] = get_order_sn($this->uid,$this->gid,$data['type']);
        $order = new Order();
        $orderId = $order->creatOrder($data);
        $order =  Order::find($orderId);
        OrderLog::addLog($order->order_no, $order->order_status, $order->type);
        return $order;
    }

    /**支付宝下单
     * @param $data
     * @return void
     */
    protected function alipay($data,$is_aiqi_cid){
        //支付宝支付
        $notify_url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/v1/api/notify/pay/alipay';//通知地址
        $return_url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/game/play/'.$data['gid'];//跳转地址
        $quit_url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/game/play/'.$data['gid'];//退出地址

        if($this->cid > 0){
            $redis = new Redis();
            $channel_data = $redis->get('channel_data_'.$data['uid']);
            $channel_url = http_build_query($channel_data);
            $return_url = $return_url.'/'.$this->cid.'?'.$channel_url;
            $quit_url = $quit_url.'/'.$this->cid.'?'.$channel_url;
        }else{
            $return_url = $return_url.'?token='.$this->token;
            $quit_url = $quit_url.'?token='.$this->token;
        }
        $pay_data = [
            'subject' => $data['goods_name'],
            'out_trade_no'=> $data['order_no'],
            'total_amount' => $data['amount'],
            'quit_url'=> $quit_url,
            'return_url'=> $return_url,
        ];

        if($is_aiqi_cid == 1){
            $result = Alipay::appPay($pay_data,$notify_url);
        }else{
            $result = Alipay::wapPay($pay_data,$notify_url);
        }
        return $result;
    }

    /**微信下单
     * @param $data
     * @return void
     */
    protected function wechat($data,$device){
        //Wap、iOS、Android
        $notify_url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/v1/api/notify/pay/weixin';//通知地址
//        $return_url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/game/pay/result/query/'.$data['gid'].'/'. $data['order_no'];
//        $quit_url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/game/pay/result/query/'.$data['gid'].'/'. $data['order_no'];

        $return_url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/game/play/'.$data['gid'];//跳转地址
        $quit_url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/game/play/'.$data['gid'];//退出地址

        $cid_arr = [5];
        if(in_array($this->cid,$cid_arr)){
            $redis = new Redis();
            $channel_data = $redis->get('channel_data_'.$data['uid']);

            $channel_url = http_build_query($channel_data);
            $return_url = $return_url.'/'.$this->cid.'?'.$channel_url;
            $quit_url = $quit_url.'/'.$this->cid.'?'.$channel_url;
        }else{
            $return_url = $return_url.'?token='.$this->token;
            $quit_url = $quit_url.'?token='.$this->token;
        }
        $pay_data = [
            'subject' => $data['goods_name'],
            'out_trade_no'=> $data['order_no'],
            'total_amount' => $data['amount'],
            'quit_url'=> urlencode($quit_url),
            'return_url'=> urlencode($return_url),
        ];
        $result = WeiXinpay::wapPay($pay_data,$notify_url,$device);
        if(!in_array($this->cid,$cid_arr)){
            $result['data']['pay_url'] = $result['data']['pay_url'].'&redirect_url='.$pay_data['quit_url'];
        }
        return $result;
    }

    /**微信内支付
     * @param $data
     * @return void
     */
    protected function wx_pay_jsapi($data){
        //Wap、iOS、Android
        $notify_url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/v1/api/notify/pay/weixin';//通知地址
//        $return_url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/game/pay/result/query/'.$data['gid'].'/'. $data['order_no'];
//        $quit_url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/game/pay/result/query/'.$data['gid'].'/'. $data['order_no'];

        $return_url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/game/play/'.$data['gid'];//跳转地址
        $quit_url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/game/play/'.$data['gid'];//退出地址
        if($this->cid > 0){
            $redis = new Redis();
            $channel_data = $redis->get('channel_data_'.$data['uid']);

            $channel_url = http_build_query($channel_data);
            $return_url = $return_url.'/'.$this->cid.'?'.$channel_url;
            $quit_url = $quit_url.'/'.$this->cid.'?'.$channel_url;
        }else{
            $return_url = $return_url.'?token='.$this->token;
            $quit_url = $quit_url.'?token='.$this->token;
        }
        $pay_data = [
            'subject' => $data['goods_name'],
            'out_trade_no'=> $data['order_no'],
            'total_amount' => $data['amount'],
            'quit_url'=> urlencode($quit_url),
            'return_url'=> urlencode($return_url),
            'openid' => get_wx_openid($this->account),
        ];
        $result = WeiXinpay::jsapiPay($pay_data,$notify_url);
        return $result;
    }

    /**
     * 支付宝订单查询
     */
    protected function alipay_query($orderNo){
        $return = false;
        return $return;
    }

    /**
     * 微信订单查询
     */
    protected function wechat_query($orderNo){
        $result = WeiXinpay::query($orderNo);

        return $result;
    }
}